package com.ruoyi.web.controller.agoniapp;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.JwtUtils;
import com.ruoyi.common.utils.TokenUser;
import com.ruoyi.common.utils.UserIdByRequest;
import com.ruoyi.system.pojo.dto.CreateTodoEventDTO;
import com.ruoyi.system.pojo.vo.TodoEventRewardVO;
import com.ruoyi.system.service.IAgoniTodoEventService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static com.ruoyi.common.core.domain.AjaxResult.success;

@RestController
@Slf4j
@RequestMapping("/agoniapp/todoEvent/")
public class TodoEventController {

    //注入事件Service
    @Autowired
    private IAgoniTodoEventService todoEventService;

    /**
     * TODO: 事件相关接口
     * 1:获取所有事件列表
     */
    @GetMapping("list")
    public AjaxResult getAllTodoEvents() {

        //TODO: 获取所有事件列表
        List<TodoEventRewardVO> events = todoEventService.getAllTodoEvents();
        //TODO: 返回事件列表
        System.out.println("events:" + events);
        return success(events);
    }

    //TODO: 根据用户id获取用户的事件列表
    @GetMapping("listByUserId")
    public AjaxResult getTodoEventsByUserId(HttpServletRequest request) {
        //TODO: 根据用户id获取用户的事件列表
        String token = request.getHeader("Authorization");

        if (token == null || !token.startsWith("Bearer ")) {
            log.warn("Token is missing or invalid");
            return AjaxResult.error("Token is missing or invalid");
        }

        token = token.substring(7); // 去掉 "Bearer " 前缀

        log.info("Token: " + token);
        TokenUser tokenUser = JwtUtils.getTokenUser(token);

        if (tokenUser == null) {
            log.warn("Invalid token");
            return AjaxResult.error("Invalid token");
        }

        Long userId = Long.valueOf(tokenUser.getId());
        log.info("用户 ID: " + userId);
        List<TodoEventRewardVO> events = todoEventService.getTodoEventsByUserId(userId);

        return success(events);

    }

    //Todo:创建事件
    @PostMapping("create")
    public AjaxResult createTodoEvent(@RequestBody CreateTodoEventDTO createTodoEventDTO,HttpServletRequest request) {
        //传递参数

        Long userId = UserIdByRequest.getUserId(request);
        int result = todoEventService.createTodoEvent(createTodoEventDTO,userId);
        //TODO: 创建事件
        return success("创建成功");
    }

    //TODO: app端撒根据id删除事件
    @DeleteMapping("deleteTodoById/{id}")
    public AjaxResult deleteTodoEvent(@PathVariable("id") Long id) {
        //TODO: 根据id删除事件
        int result = todoEventService.deleteTodoEvent(id);
        if (result == 1) {
            return success("删除成功");
        } else {
            return AjaxResult.error("删除失败");
        }
    }


}
